<template>
  <div class="home-container">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item
        v-for="crumb in breadcrumbs"
        :key="crumb.id"
        :to="crumb.path"
      >
        {{ crumb.name }}
      </el-breadcrumb-item>
    </el-breadcrumb>
    <div class="toolbar">
      <div class="button-group">
        <el-button type="primary" :icon="Upload" @click="onUpload"
          >上传</el-button
        >
        <el-button type="primary" :icon="Folder" @click="onCreate"
          >新建</el-button
        >
        <el-dropdown :disabled="!selectedIds.length > 0">
          <el-button type="primary" :icon="More">更多</el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="onBatchDownload">下载</el-dropdown-item>
              <el-dropdown-item @click="onBatchMove">移动</el-dropdown-item>
              <el-dropdown-item @click="onBatchRecycle">删除</el-dropdown-item>
              <el-dropdown-item @click="onBatchShare">分享</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button type="primary" :icon="Refresh" @click="onRefresh"
          >刷新</el-button
        >
      </div>
      <div class="search-input">
        <el-input
          v-model="searchText"
          clearable
          prefix-icon="Search"
          placeholder="搜索文件"
        />
      </div>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      ref="multipleTableRef"
      row-key="id"
      @sortChange="onSortChange"
      @selection-change="onSelectionChange"
    >
      <!-- 选择框 -->
      <el-table-column type="selection" width="48" />
      <!-- 文件图标 -->
      <el-table-column
        prop="type"
        label="类型"
        width="55"
        class-name="icon-column"
      >
        <template #default="{ row }">
          <div @click="onClickFilename(row)">
            <el-image
              :src="getCoverUrl(row)"
              v-if="
                row.type.startsWith('image/') || row.type.startsWith('video/')
              "
            />
            <svg class="file-icon" aria-hidden="true" v-else>
              <use :xlink:href="`#${getFileIconId(row.type)}`" />
            </svg>
          </div>
        </template>
      </el-table-column>
      <!-- 文件名 -->
      <el-table-column
        prop="filename"
        sortable="custom"
        label="文件名"
        min-width="100"
        class-name="filename-column"
      >
        <template #default="{ row }">
          <span @click="onClickFilename(row)" v-if="row.id !== editFile.id">
            {{ row.filename }}
          </span>
          <!-- 修改文件名 -->
          <el-input
            v-else
            ref="editInputRef"
            v-model="editFile.name"
            @blur="onConfirm"
          >
            <template #suffix>{{ editFile.ext }}</template>
          </el-input>
        </template>
      </el-table-column>
      <!-- 操作 -->
      <el-table-column
        label="操作"
        min-width="100"
        align="right"
        v-if="!isFold"
      >
        <template #default="{ row }">
          <div class="action-buttons">
            <el-button link type="info" size="small" @click="onFileInfo(row)"
              >详情</el-button
            >
            <el-button link type="warning" size="small" @click="onRename(row)"
              >重命名</el-button
            >
            <el-button link type="primary" size="small" @click="onShare(row)"
              >分享</el-button
            >
            <el-button link type="primary" size="small" @click="onDownload(row)"
              >下载</el-button
            >
            <el-button link type="primary" size="small" @click="onMove(row)"
              >移动</el-button
            >
            <el-button link type="primary" size="small" @click="onCopyTo(row)"
              >复制到</el-button
            >
            <el-popconfirm
              title="确定要删除吗?"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="() => onRecycle(row)"
            >
              <template #reference>
                <el-button link type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
      <!-- 文件大小 -->
      <el-table-column
        prop="size"
        sortable="custom"
        label="大小"
        width="150"
        v-if="!isFold"
      >
        <template #default="{ row }">
          {{ formatFileSize(row.size) }}
        </template>
      </el-table-column>
      <!-- 修改日期 -->
      <el-table-column
        prop="updatedAt"
        sortable="custom"
        label="修改日期"
        width="150"
        v-if="!isFold"
      >
        <template #default="{ row }">
          {{ formatToDateTime(row.updatedAt) }}
        </template>
      </el-table-column>
      <!-- 展开折叠 -->
      <el-table-column type="expand" v-if="isFold">
        <template #default="props">
          <div class="expand-content">
            <div class="expand-info">
              <el-text type="info">{{
                formatToDateTime(props.row.createdAt)
              }}</el-text>
              <el-text type="info">{{
                formatFileSize(props.row.size)
              }}</el-text>
            </div>
            <el-button-group>
              <el-button type="info" size="small" @click="onFileInfo(props.row)"
                >详情</el-button
              >
              <el-button
                type="warning"
                size="small"
                @click="onRename(props.row)"
                >重命名</el-button
              >
              <el-button type="primary" size="small" @click="onShare(props.row)"
                >分享</el-button
              >
              <el-button type="primary" size="small" @click="onMove(props.row)"
                >移动</el-button
              >
              <el-popconfirm
                title="确定要删除吗?"
                confirm-button-text="确定"
                cancel-button-text="取消"
                @confirm="() => onRecycle(props.row)"
              >
                <template #reference>
                  <el-button type="danger" size="small">删除</el-button>
                </template>
              </el-popconfirm>
            </el-button-group>
          </div>
        </template>
      </el-table-column>
      <!-- 空状态 -->
      <template #empty>
        <el-empty :description="emptyDescription" />
      </template>
    </el-table>

    <el-pagination
      layout="total, prev, pager, next, sizes, jumper"
      :page-sizes="[10, 50, 100, 300]"
      v-model:current-page="current"
      v-model:page-size="pageSize"
      :total="total"
      @update:current-page="debouncedLoadData"
      @update:page-size="debouncedLoadData"
      background
      class="pagination"
    />
  </div>
  <!-- 预览组件 -->
  <Preview ref="previewRef" />

  <FileInfoDialog ref="fileInfoDialogRef" />
  <ShareDialog ref="shareDialogRef" />
  <MoveDialog ref="moveDialogRef" @finish="loadData" />
  <UploadDialog ref="uploadDialogRef" @onUploadSuccess="loadData" />
</template>
<script setup>
import { Upload, Folder, More, Refresh } from "@element-plus/icons-vue";
import { ref, watch, computed, onUnmounted, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  getPageApi,
  recycleFileApi,
  recycleFilesApi,
  getFileInfoApi,
  downloadFileApi,
  getFileUrlApi,
  renameApi,
  createFolderApi,
  downloadFolderApi,
  downloadFilesApi
} from "../api";
import { ElMessage } from "element-plus";
import { formatToDateTime, formatFileSize } from "../utils/FormatUtil";
import Confirm from "../utils/Confirm";
import { getFileIconId } from "../utils/FileIconId";
import FileInfoDialog from "../components/FileInfoDialog.vue";
import ShareDialog from "../components/ShareDialog.vue";
import MoveDialog from "../components/MoveDialog.vue";
import UploadDialog from "../components/UploadDialog.vue";
import Preview from "../components/preview/Preview.vue";
import { debounce } from "lodash-es";
import { useStore } from "../stores";
import { useWindowSize } from "@vueuse/core";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const { width } = useWindowSize();
const isFold = computed(() => width.value < 900);

const route = useRoute();
const router = useRouter();
const store = useStore();
const multipleTableRef = ref(null);
const fileInfoDialogRef = ref(null);
const shareDialogRef = ref(null);
const moveDialogRef = ref(null);
const uploadDialogRef = ref(null);
const editInputRef = ref(null);

const tableData = ref([]); //表格数据
const current = ref(1); // 当前页
const pageSize = ref(50); // 每页条目数
const total = ref(0); // 数据总条目数
const currentFolder = ref(null);

const sortField = ref("");
const sortOrder = ref("descending");

const searchText = ref("");
const loading = ref(false); // 加载状态

const selectedIds = ref([]); // 选中的文件ID列表

const previewRef = ref();

//文件夹改名
const editFile = ref({
  isUpdate: false,
  originalName: "",
  id: "",
  name: "",
  ext: "",
});

const loadData = async () => {
  if (loading.value) {
    return;
  }
  loading.value = true;
  try {
    const res = await getPageApi(
      route.params.parentId,
      pageSize.value,
      current.value,
      searchText.value,
      sortField.value,
      sortOrder.value
    );
    if (route.params.parentId) {
      const res = await getFileInfoApi(route.params.parentId);
      currentFolder.value = res.data;
    } else {
      currentFolder.value = null;
    }
    tableData.value = res.data.list;
    total.value = res.data.total;
  } catch (error) {
    console.error("加载文件列表失败:", error);
    throw error;
  } finally {
    loading.value = false;
  }
};

const debouncedLoadData = debounce(loadData, 300);

watch(
  () => route.params.parentId,
  () => {
    current.value = 1;
    debouncedLoadData();
  },
  { immediate: true }
);
watch(searchText, () => {
  current.value = 1;
  debouncedLoadData();
});

const breadcrumbs = computed(() => {
  const crumbs = [{ name: "我的空间", path: "/home", id: null }];
  if (!currentFolder.value) return crumbs;

  const folderChain = [];
  let folder = currentFolder.value;
  while (folder) {
    folderChain.unshift({
      // 添加到数组开头保证顺序正确
      name: folder.filename,
      path: `/home/${folder.id}`,
      id: folder.id,
      isTop: folder.parent == null && !folder.parentId  ? true : false,
    });
    folder = folder.parent;
  }

  if (!folderChain[0].isTop) {
    crumbs.push({ name: "...", path: "", id: "" });
  }
  crumbs.push(...folderChain);
  return crumbs;
});

const emptyDescription = computed(() => {
  if (searchText.value) {
    return "没有找到相关内容";
  } else if (route.params.parentId) {
    return "该目录下没有任何内容";
  } else {
    return "欢迎使用个人空间，您可以上传文件、创建文件夹等操作";
  }
});

//按钮操作

const onUpload = () => {
  uploadDialogRef.value.open(route.params.parentId || null);
};
const onCreate = (e) => {
  tableData.value.unshift({
    id: "fileId",
    filename: "新建文件夹",
    type: "folder",
    size: 0,
  });
  editFile.value.isUpdate = false;
  editFile.value.id = "fileId";
  editFile.value.originalName = "新建文件夹";
  editFile.value.name = "新建文件夹";
  editFile.value.ext = "";
  nextTick(() => {
    editInputRef.value?.focus();
  });
};

const onBatchRecycle = async () => {
  Confirm("确定要删除这些文件吗?", async () => {
    try {
      await recycleFilesApi(selectedIds.value);
      loadData();
    } catch (error) {
      console.error("删除文件失败:", error);
    }
  });
};

const getCoverUrl = (row) => {
  return `${import.meta.env.VITE_BASE_URL}uploads/covers/${row.hash}.jpg`;
};

const onBatchMove = () => {
  moveDialogRef.value.open(selectedIds.value);
};

const onBatchShare = () => {
  ElMessage.warning(
    "暂不支持批量分享。如需分享多个分散的文件，建议先将它们移动到临时文件夹内再分享。"
  );
};

const onBatchDownload = async () => {
  try {
    const res = await downloadFilesApi(selectedIds.value);
    console.log("获取了签名" + res); 
    const url = import.meta.env.VITE_BASE_URL + 'api/file/download/url/'+ res.signature;
    window.open(url);

  } catch (error) {
    console.error("下载文件失败:", error);
  }
}

const onRefresh = async () => {
  try {
    await loadData();
    ElMessage.success("刷新成功");
  } catch (error) {
    console.error("刷新失败:", error);
  }
};

const onSortChange = ({ prop, order }) => {
  sortField.value = prop;
  sortOrder.value = order;
  loadData();
};

//文件项目操作
const onSelectionChange = (e) => {
  selectedIds.value = e.map((item) => item.id);
};
const onFileInfo = (row) => {
  fileInfoDialogRef.value.open(row);
};
const onRename = (row) => {
  editFile.value.isUpdate = true;
  editFile.value.id = row.id;
  editFile.value.originalName = row.filename;
  nextTick(() => {
    editInputRef.value?.focus();
  });
  if (row.isFolder) {
    editFile.value.name = row.filename;
    editFile.value.ext = "";
  } else {
    editFile.value.name = row.filename.substring(
      0,
      row.filename.lastIndexOf(".")
    );
    editFile.value.ext = row.filename.substring(row.filename.lastIndexOf("."));
  }
};

const onConfirm = async () => {
  if (!editFile.value.isUpdate) {
    if (editFile.value.name.trim() === "") {
      ElMessage.warning("文件夹名不能为空");
      return;
    }
    try {
      const parentId = currentFolder.value?.id || null;
      const res = await createFolderApi(
        parentId,
        editFile.value.name.trim()
      );
      editFile.value.id = null;
      loadData();
    } catch (error) {
      console.error("创建文件夹失败:", error);
    }
    return;
  }
  const newFilename = editFile.value.name.trim();
  if (!newFilename) {
    ElMessage.warning("文件名不能为空");
    editFile.value.id = null;
    return;
  }
  if (newFilename.includes("/")) {
    ElMessage.warning("文件名不能包含 '/' 字符");
    editFile.value.id = null;
    return;
  }
  if (newFilename + editFile.value.ext === editFile.value.originalName) {
    editFile.value.id = null;
    return;
  }
  try {
    await renameApi(editFile.value.id, newFilename + editFile.value.ext);
    editFile.value.id = null;
    loadData();
  } catch (error) {
    console.error("重命名文件失败:", error);
  }
};
const onShare = (row) => {
  shareDialogRef.value.open(row);
};
const onMove = (row) => {
  moveDialogRef.value.open(row.id, 'move');
};
const onCopyTo = (row) => {
  moveDialogRef.value.open(row.id, 'copy');
}
const onDownload = async (row) => {
  if (row.type === "folder") {
    try{
      const res = await downloadFolderApi(row.id);
      console.log("获取了签名" + res);
      const url = import.meta.env.VITE_BASE_URL + 'api/file/download/url/'+ res.signature;

      window.open(url);
      return;
    }catch(error){
      console.error("下载文件夹失败:", error);
    }
  }
  if (row.size < 1024 * 1024 * 1) {
    ElMessage.warning("文件小于1M，直接下载");
    try {
      await downloadFileApi(row.id, row.filename);
    } catch (error) {
      console.error("下载文件失败:", error);
    }
    return;
  } else {
    //大文件使用浏览器下载
    try {
      const res = await getFileUrlApi(row.id);
      console.log("获取了签名" + res);
      const url = import.meta.env.VITE_BASE_URL + 'api/file/download/url/'+ res.signature;
      window.open(url);
    } catch (error) {
      console.error("获取下载链接失败:", error);
    }
  }
};
const onClickFilename = (row) => {
  if (row.type === "folder") {
    router.push(`/home/${encodeURIComponent(row.id)}`);
  } else {
    previewRef.value.showPreview(row, 1);
  }
};
const onRecycle = async (row) => {
  try {
    await recycleFileApi(row.id);
    loadData();
  } catch (error) {
    console.error("删除文件失败:", error);
  }
};

onUnmounted(() => {
  debouncedLoadData.cancel();
});
</script>

<style scoped>
:deep(.icon-column .cell) {
  padding: 0px !important;
}
:deep(td.filename-column .cell:hover) {
  text-decoration: underline;
}
:deep(td.filename-column .cell) {
  cursor: pointer;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}
</style>
